package com.lagou.edu.service.impl;

import com.lagou.edu.pojo.LagouToken;
import com.lagou.edu.dao.LagouTokenDao;
import com.lagou.edu.service.LaGouServiceCodeClient;
import com.lagou.edu.service.UserService;
import com.lagou.edu.util.AESUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: jie.zhao
 * @create: 2021/07/31 14:13
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    LagouTokenDao lagouTokenDao;

    @Autowired
    LaGouServiceCodeClient laGouServiceCodeClient;

    @Override
    public boolean isRegistered(String email) {
        LagouToken lagouToken = lagouTokenDao.findByEmail(email);
        if(lagouToken==null){
            return false;
        }
        return true;
    }

    @Override
    public String login(String email, String password, HttpServletResponse httpServletResponse) {
        if(!email.endsWith(".com")){
            return "用户名不合法";
        }
        String sourcetk = email + ":" + password;
        String token = AESUtil.LoginEncrypt(sourcetk);
        Cookie ck = new Cookie("respAddCK",token);
        httpServletResponse.addCookie(ck);
        return "登录成功";
    }

    @Override
    public String register(String email, String password, String code) {

        Integer result = laGouServiceCodeClient.validate(email,code);
        if(result!=0){
            return "2";
        }
        String sourcetk = email + "=" + password;
        String token = AESUtil.LoginEncrypt(sourcetk);
        LagouToken lagouToken = new LagouToken();
        lagouToken.setToken(token);
        lagouToken.setEmail(email);
        lagouTokenDao.save(lagouToken);
        return "0";
    }


}
